/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dahg.project.controller.model.beans.impl;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import org.dahg.project.controller.model.Usuario;
import org.dahg.project.controller.model.beans.AbstractBean;
import org.dahg.project.controller.model.exceptions.ControllerException;
import org.dahg.project.controller.model.exceptions.ValidationException;
import org.dahg.project.controller.model.services.local.UsuarioService;

/**
 *
 * @author dahg
 */
@Stateless
public class UsuarioServiceImpl extends AbstractBean<Usuario> implements UsuarioService {	
	
	@Override
	protected Class<Usuario> getClazz() {
		return Usuario.class;
	}

	@Override
	public Usuario validate(String user, String pass) throws ValidationException,ControllerException {
		boolean existe = getById(user)!=null;
		if(!existe) throw new ValidationException("Usuario incorrecto");
		
		Usuario usuario=null;
		String jpql="Select u From Usuario u where u.id=:id and u.contrasena=:pass";
		Query query = getEntityManager().createQuery(jpql);
		query.setParameter("id", user);
		try {
			query.setParameter("pass", getDecrypt().hash(pass));
			usuario = (Usuario) query.getSingleResult();			
		} 
		catch(NoResultException e) {
			throw new ValidationException("Contrasena incorrecta");
		}
		catch (Exception e) {
			throw new ControllerException(e);
		}
		
		return usuario;
	}

    @Override
    public void remove(Usuario obj) {		
        String sql="delete from Usuario u where u.id=:id";
        this.remove(sql, obj.getId());
    } 

    @Override
    public List<Usuario> getAll() {
        String query = "select u From Usuario u order by u.id";
        Query q = getEntityManager().createQuery(query);
        return q.getResultList();
    }

    @Override
    public void persist(Usuario obj) throws ControllerException {
        String encrypt="";
        try {
            encrypt = getDecrypt().hash(obj.getContrasena());
        } catch (Exception ex) {
            Logger.getLogger(UsuarioServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        obj.setContrasena(encrypt);
        super.persist(obj);
    }

    @Override
    public void merge(Usuario obj) {
        String encrypt="";
        try {
            encrypt = getDecrypt().hash(obj.getContrasena());
        } catch (Exception ex) {
            Logger.getLogger(UsuarioServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        obj.setContrasena(encrypt);
        super.merge(obj);
    }
    
    
}
